package com.qzdsoft.erpcloud.controller.proj;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.qzdsoft.common.domain.query.sys.QueryParams;
import com.qzdsoft.erpcloud.controller.BaseController;
import com.qzdsoft.erpcloud.domain.proj.Bom;
import com.qzdsoft.erpcloud.domain.proj.BomItem;
import com.qzdsoft.erpcloud.domain.sys.LoginUser;
import com.qzdsoft.erpcloud.service.basic.DataDictionaryValueService;
import com.qzdsoft.erpcloud.service.proj.BomService;
import com.qzdsoft.erpcloud.service.proj.MaterialInfoService;
import com.qzdsoft.erpcloud.service.sys.Permission;
import com.qzdsoft.erpcloud.service.sys.SysLog;
import com.qzdsoft.erpcloud.vo.proj.BomDetailEditInfo;
import com.qzdsoft.erpcloud.vo.proj.BomInfo;
import com.qzdsoft.erpcloud.vo.proj.BomItemInfo;
import com.qzdsoft.erpcloud.vo.proj.BomQueryInfo;
import com.qzdsoft.erpcloud.vo.proj.MaterialInfoQueryInfo;
import com.qzdsoft.erpcloud.vo.proj.ProjMaterialBomInfo;
import com.qzdsoft.erpcloud.vo.pu.PurchaseOrderDetailRemoveInfo;
import com.qzdsoft.utils.ExceptionUtil;
import com.qzdsoft.vo.LayTableResponse;
import com.qzdsoft.vo.Response;
import com.qzdsoft.vo.ResultEnum;

/**
 * Created by zhanghao
 * 物料清单
 */

@Controller
@RequestMapping("/eng/bom")
public class BomController extends BaseController{
    private static final String BASEPATH = "eng/bom";

    private static final Logger logger = LoggerFactory.getLogger(BomController.class);
    @Autowired
    private BomService bomService;
    @Autowired
    private DataDictionaryValueService enumValueService;
    @Autowired
    private MaterialInfoService materialService;
    
    
    /**
     * BOM信息 初始化页面
     * @param request
     * @param model
     * @param params
     * @return
     */
    @Permission(validate=false)
    @RequestMapping(value = "index", method = RequestMethod.GET)
    public ModelAndView index(HttpServletRequest request,QueryParams params){
        ModelAndView mv = new  ModelAndView();
     // 获取物料分类信息 列表 根据分组id 拿数据
        mv.addObject("materialTypeList", enumValueService.getByEnumId(7));
        // 获取物料品牌信息 列表
        mv.addObject("materialBrandList", enumValueService.getByEnumId(2));
        mv.setViewName("eng/bom/index");
        return mv;
    }

    /**
     * 初始化网格数据
     * @param request
     * @param model
     * @param params
     * @return
     */
    @Permission(validate=false)
    @RequestMapping("/data")
    @ResponseBody
    public LayTableResponse<BomInfo> list(int page, int limit)throws Exception{
        // layui table 网格数据源
        LayTableResponse<BomInfo> tabledata = bomService.findPage(page, limit);
        return tabledata;
    }
    
    /**
     * 初始化网格数据
     * @param request
     * @param model
     * @param params
     * @return
     */
    @RequestMapping("/search")
    @ResponseBody
    public LayTableResponse<BomInfo> list(BomQueryInfo search)throws Exception{
        // layui table 网格数据源
        LayTableResponse<BomInfo> tabledata = bomService.findPageByItems(search);
        return tabledata;
    }
    
    /**
     * BOM父件新增页面 
     * @param companyid
     * @param id
     * @return
     */
    @Permission(validate=false)
    @RequestMapping("/goforadd")
    public ModelAndView addview(int companyid, Integer id){
        ModelAndView mv = new ModelAndView();
        // 获取物料分类信息 列表 根据分组id 拿数据
        mv.setViewName(BASEPATH + "/addinfo");
        return mv;
    }
    
	/**
	 * 新增保存父件信息
	 * @param bom
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/addBom")
	public Response<String> addBom(@ModelAttribute Bom bom, HttpServletRequest request)
			throws Exception {
		LoginUser loginUser = getUser();
		// 提交保存
		return bomService.addBom(bom, loginUser);
	}
	
	/**
	 * BOM父件修改页面 
	 * @param companyid
	 * @param id
	 * @return
	 */
	@Permission(validate=false)
	@RequestMapping("/goforedit")
	public ModelAndView editview(int companyid, Integer id){
	    ModelAndView mv = new ModelAndView();
	    mv.addObject("entity", this.bomService.getBomById(id));
	    // 获取物料分类信息 列表 根据分组id 拿数据
	    mv.setViewName(BASEPATH + "/editinfo");
	    return mv;
	}
	
	/**
	 * 修改保存父件信息
	 * @param bom
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/editBom")
	public Response<String> editBom(@ModelAttribute Bom bom, HttpServletRequest request)
	        throws Exception {
	    LoginUser loginUser = getUser();
	    // 提交保存
	    return bomService.editBom(bom, loginUser);
	}
	/**
	 * 
	 * @param bomId
	 * @return
	 */
	@Permission(validate=false)
	@ResponseBody
    @RequestMapping("/childedit")
	public ModelAndView index(Integer bomId) {
        //查询采购订单
        BomInfo bom = this.bomService.getBomById(bomId);
        ModelAndView mv = new ModelAndView();
        mv.addObject("bom",bom);
        mv.setViewName(BASEPATH + "/bomdetail");
        return mv;
    }
	
	/**
	 * bom 子件新增
	 * @param childbom
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/addChildBom", method = RequestMethod.POST)
	public Response<String> addChildBom(@ModelAttribute BomItem childbom, HttpServletRequest request)
			throws Exception {
        LoginUser loginUser = getUser();
		// 提交保存
		return bomService.addChildBom(childbom, loginUser);
	}
	
	/**
	 * Bom新增或者修改
	 * @param bom
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/editChildById")
	public Response<String> editBOMBom(@ModelAttribute BomItem bomchild ,String oper, HttpServletRequest request)
			throws Exception {
        LoginUser loginUser = getUser();
		//如果row_data 为空
		return bomService.editChildBom(bomchild, loginUser);
	}
	/**
	 * 
	 * @param request
	 * @param response
	 * @param page
	 * @param rows
	 * @return
	 * @throws IOException
	 */
	@Permission(validate=false)
	@ResponseBody
    @RequestMapping("/getChildByBomId")
    public Object getChildByBomId(HttpServletRequest request,HttpServletResponse response,int page,int rows,int bomId) throws IOException {
    	 String jsondata = bomService.getChildByBomId( rows, page,bomId);
    	 response.setContentType("text/JavaScript; charset=utf-8"); 
		return jsondata;
    }
	
	/**
	 * 删除子件信息
	 * 
	 * @param id
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/deleteMaterial", method = RequestMethod.POST)
	public Response<String> deleteMenu(Integer id, HttpServletRequest request) {
		// 检查session
        LoginUser loginUser = getUser();
		return bomService.delteBomItem(id, loginUser);
	}
	/**
	 * 删除整个BOM信息
	 * id 为父件ID
	 * @param id
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/deleteBom")
	public Response<String> deleteBom(Integer id, HttpServletRequest request) {
		// 检查session
        LoginUser loginUser = getUser();
		return bomService.delBomById(id, loginUser);
	}
	
	/**
     * 审核
     * @param id
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/audt")
    public Response<String> audtById(Integer id, HttpServletRequest request) throws Exception {
        // 检查session
        LoginUser loginUser = getUser();
        return bomService.audtById(id, loginUser);
    }
    
    /**
     * 弃审
     * @param id
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/unaudt")
    public Response<String> unAudtById(Integer id, HttpServletRequest request) throws Exception {
        // 检查session
        LoginUser loginUser = getUser();
        return bomService.unAudtById(id, loginUser);
    }
    /*************************** BOM 父件相关****************************************/
    /**
     * 跳转到页面
     * @return
     */
    @Permission(validate=false)
    @RequestMapping("/bomdetails")
    public ModelAndView item(Integer bomId,BomQueryInfo queryinfo)
    {
        ModelAndView mv = new ModelAndView();
        //查询BOM 父件信息
        BomInfo bom = this.bomService.getBomById(bomId);
        mv.addObject("bom",bom);
        
        //明细列表
        List<BomItemInfo> list = bomService.getBomChildByBomId(bomId,queryinfo);
        mv.addObject("details",list);
        mv.setViewName(BASEPATH + "/detailItem");
        return mv;
    }
    
    /**
     * 跳转到页面
     * @return
     */
    @SysLog(description="编辑BOM子件明细")
    @ResponseBody
    @RequestMapping("/edit-bomitem")
    public Response<String> bomitemedit(@RequestBody BomDetailEditInfo info) {
        try
        {
            return bomService.bomitemedit(info);
        }
        catch (Exception ex)
        {
            logger.error("编辑BOM子件错误，错误信息：{}", ExceptionUtil.getStackTrace(ex));
        }
        return new Response<String>(ResultEnum.ERROR);
    }
    
    @SysLog(description="BOM子件删除")
    @ResponseBody
    @RequestMapping("/bomitem-remove")
    public Response<String> remove(@RequestBody PurchaseOrderDetailRemoveInfo info){
        try
        {
            logger.debug("bom子件详情删除，ids：{}",info.getIds());
            return bomService.removebomitem(info.getIds());
        }
        catch (Exception ex)
        {
            logger.error("删除BOM子件错误，错误信息：{}", ExceptionUtil.getStackTrace(ex));
        }
        return new Response<String>(ResultEnum.ERROR);
    }
    
    /**
     * 物料选择页面
     * @return
     */
    @Permission(validate=false)
    @RequestMapping("/selectmaterials")
    public ModelAndView selectMaterial() {
        ModelAndView view = new ModelAndView();
        view.setViewName(BASEPATH+"/materials");
        return view;
    }
    
    /**
     * 物料选择页面
     * @return
     */
    @Permission(validate=false)
    @RequestMapping("/bomchange")
    public ModelAndView bomChange() {
        ModelAndView view = new ModelAndView();
        view.setViewName(BASEPATH+"/bomchange");
        return view;
    }
    
    /**
     * 查询物料信息
     * @param info
     * @return
     */
    @Permission(validate=false)
    @ResponseBody
    @RequestMapping("/materias")
    public LayTableResponse<ProjMaterialBomInfo> list(MaterialInfoQueryInfo info){
        //加载所有生产耗用为true 的存货
        info.setIsProdConsumption(true);
        info.setIsNoUsed(false);
        info.setIsDefault(true);
        return materialService.selectPageBy(info);
    }
    /**
     * 查询物料信息
     * @param info
     * @return
     */
    @Permission(validate=false)
    @ResponseBody
    @RequestMapping("/bomversions")
    public LayTableResponse<ProjMaterialBomInfo> bomversionslist(MaterialInfoQueryInfo info){
        //加载所有生产耗用为true 的存货
        info.setIsProdConsumption(true);
        info.setIsNoUsed(false);
        return materialService.selectBomVersionByMaterialId(info);
    }
}
